package session

import (
	"errors"
	"sync"
)

// 内存的session, 是session接口的实现

// 定义对象
type MemorySeession struct {
	sessionId string
	// 存kv
	data   map[string]interface{}
	rwlock sync.RWMutex
}

// 构造函数
func NewMemorySession(id string) *MemorySeession {
	return &MemorySeession{
		sessionId: id,
		data:      make(map[string]interface{}, 16),
	}
}

func (m *MemorySeession) Set(key string, value interface{}) (err error) {
	// 加锁
	m.rwlock.Lock()
	defer m.rwlock.Unlock()

	// 设置值
	m.data[key] = value
	return
}
func (m *MemorySeession) Get(key string) (value interface{}, err error) {
	// 加锁
	m.rwlock.Lock()
	defer m.rwlock.Unlock()

	// 获取值
	value, ok := m.data[key]
	if !ok {
		err = errors.New("key not exists in session")
		return
	}
	return
}
func (m *MemorySeession) Del(key string) (err error) {
	// 加锁
	m.rwlock.Lock()
	defer m.rwlock.Unlock()

	// 删除
	delete(m.data, key)
	return
}
func (m *MemorySeession) Save() (err error) {
	return
}
